<template>
  <div class="ui bottom" style="text-align:center">
    <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-count="totalPage"
                   layout="prev, pager, next" background hide-on-single-page>
    </el-pagination>
  </div>
</template>

<script setup>
import {onActivated, ref, nextTick, getCurrentInstance} from "vue";
import {useState} from "@/util/useState";
import {useRoute} from "vue-router";

const {proxy} = getCurrentInstance()
const props = defineProps({
  getBlogList: {
    type: Function,
    required: true
  },
  totalPage: {
    type: Number,
    required: true
  }
});

const pageNum = ref(1)
const {isBlogToHome, clientSize} = useState(['isBlogToHome', 'clientSize'])
const route = useRoute();

onActivated(() => {
  nextTick(() => {
    if (!isBlogToHome.value) {
      //从其它页面路由到首页时，让首页的分页组件页码重置到第一页
      pageNum.value = 1
    }
  })
})

//监听页码改变的事件
function handleCurrentChange(newPage) {
  //如果是首页，则滚动至Header下方
  if (route.name === 'home') {
    window.scrollTo({top: clientSize.value.clientHeight, behavior: 'smooth'})
  } else {
    //其它页面（分类和标签页）滚动至顶部
    proxy.scrollToTop()
  }
  pageNum.value = newPage
  props.getBlogList(newPage)
}
</script>

<style scoped>
.el-pagination.is-background .btn-next, .el-pagination.is-background .btn-prev, .el-pagination.is-background .el-pager li {
  background-color: #ffffff !important;
}

.el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #409EFF !important;
}
</style>
